/*
 * main.c
 *
 *  Created on: 16/apr/2014
 *      Author: kappa
 */

#include <stdio.h>

#include "lib/cmd.h"
#include "lib/config.h"
#include "lib/utils/logger.h"
#include "lib/utils/errors.h"
#include "lib/utils/semaphores.h"
#include "lib/utils/sharedMemory.h"
#include "lib/utils/mmap.h"
#ifdef _WIN32
#include <Windows.h>
#else
#include <unistd.h>
#include "lib/utils/daemon.h"
#endif


//extern int regSemId;
//extern int usrInOutSemId;
char * secretsFile;
int secretsFileSize;
int main (int argc, char *argv[]){

	SRV_CNF configuration;
#ifndef _WIN32
/*if(already_running()==0){
		daemonize(DNAME);
}*/
#endif

//	extern MBOXSEM *mBoxSems;
//	extern int mBoxSemsSize;
	struct sockaddr_in serverSmtpSocket;
	struct sockaddr_in serverPop3Socket;

	unsigned int smtpServSockId = -1;
	unsigned int  smtpClientSockId = -1;
	unsigned int pop3ServSockId = -1;
	unsigned int  pop3ClientSockId = -1;

	int smtpListenerPID = 0;
	int pop3ListenerPID = 0;



	initLogger();
	logMessage(INFO_LEV,"Richiedo la configurazione ....");
	initConfigObject(&configuration);
//	printConfiguration(&configuration);
	getConfiguration(&configuration);
//	printConfiguration(&configuration);
	logMessage(INFO_LEV," .... OK.");

	secretsFile = (char *)mapFullFileShared(configuration.secretsFile, &secretsFileSize);

	initMBoxSems(secretsFile, secretsFileSize);
	//TODO: Funzione che dealloca tutti semafori clearMBoxSems

	/*Partenza processo di ascolto sulla porta POP3*/
	if((pop3ListenerPID = fork()) == 0){
		startPop3Listener(&configuration, &pop3ServSockId, &pop3ClientSockId, &serverPop3Socket);
	}
	if(pop3ListenerPID < 0){
		notifyError(ERR_PROC_CREATE, 1, 0);
	}
	/*Partenza processo di ascolto sulla porta SMTP*/
	if((smtpListenerPID  = fork()) == 0){
		startSmtpListener(&configuration, &smtpServSockId, &smtpClientSockId, &serverSmtpSocket);
	}
	if(smtpListenerPID < 0){
		notifyError(ERR_PROC_CREATE, 1, 0);
	}

	for(;;)sleep(1);


	freeMBoxSems();
	logMessage(INFO_LEV," TERMINAZIONE ESECUZIONE PKMAILSO.");
	closeMappedFile(secretsFile, &secretsFileSize);
	closeLogger();
	exit(0);
}

/*Inizializzo il semaforo di mutua esclusione sulla lista dei semafori di mutua esclusione sulle inbox degli utenti*/
//	usrInOutSemId = binSemAlloc(IPC_PRIVATE, IPC_CREAT | SEM_UNDO);
//	binSemInit(usrInOutSemId);
//	initUsrInOutSemList();
